
import { PlusOutlined } from '@ant-design/icons';
import type { ActionType, ColumnsState, ProColumns, ProDescriptionsItemProps } from '@ant-design/pro-components';
import {
  FooterToolbar,
  ModalForm,
  PageContainer,
  ProDescriptions,
  ProFormText,
  ProFormTextArea,
  ProTable,
} from '@ant-design/pro-components';
import { FormattedMessage, useIntl } from '@umijs/max';
import { Button, Drawer, Input, message, Modal } from 'antd';
import React, { useRef, useState } from 'react';
import { faL } from '@fortawesome/free-solid-svg-icons';
import EditForm from './components/EditForm';
import { pagedAPi, activeSp } from '@/services/channel/sp_api';
import dayjs from 'dayjs';
import ApiRelationModal from './components/ApiRelationModal';
import { formatToLocalTime,toUTC } from '@/utils/time';



const TableList: React.FC = () => {
  /**
   * @en-US Pop-up window of new window
   * @zh-CN 新建窗口的弹窗
   *  */
  const [createModalOpen, handleModalOpen] = useState<boolean>(false);
  /**
   * @en-US The pop-up window of the distribution update window
   * @zh-CN 分布更新窗口的弹窗
   * */
  const [updateModalOpen, handleUpdateModalOpen] = useState<boolean>(false);
  const [apiModalOpen, handleApiModalOpen] = useState<boolean>(false);

  const [showDetail, setShowDetail] = useState<boolean>(false);

  const actionRef = useRef<ActionType>();
  const [currentRow, setCurrentRow] = useState<ServiceProvider>();
  const [selectedRowsState, setSelectedRows] = useState<ServiceProvider[]>([]);

  /**
   * @en-US International configuration
   * @zh-CN 国际化配置
   * */
  const intl = useIntl();
  const makeActive = (id: string, status: number) => {
    Modal.confirm({
      title: intl.formatMessage({ id: "pages.confirm.title" }),
      content: intl.formatMessage(
        { id: "pages.confirm.content" },
        {
          action: intl.formatMessage({
            id: status === 0 ? "pages.activate" : "pages.deactivate",
          }),
        }
      ),
      okText: intl.formatMessage({ id: "pages.confirm.okText" }),
      cancelText: intl.formatMessage({ id: "pages.confirm.cancelText" }),
      onOk: async () => {
        const hide = message.loading(
          intl.formatMessage({ id: "pages.processing" })
        );
        try {
          await activeSp({ asId: id, asStatus: status });
          hide();
          message.success(
            intl.formatMessage({
              id:
                status === 0
                  ? "pages.success.activate"
                  : "pages.success.deactivate",
            })
          );
          if (actionRef.current) {
            actionRef.current.reload();
          }
        } catch (error) {
          hide();
          message.error(intl.formatMessage({ id: "request.error.retry" }));
        }
      },
    });
  };

  const columns: ProColumns<ServiceProvider>[] = [
    {
      title: (
        <FormattedMessage
          id="pages.sp.code"
        />
      ),
      dataIndex: 'spCode',
    },
    {
      title: <FormattedMessage id="pages.sp.name" />,
      dataIndex: 'spName',
    },

    {
      title: <FormattedMessage id="pages.sp.status" defaultMessage="Status" />,
      dataIndex: 'spStatus',
      hideInForm: true,
      valueEnum: {
        '1': {
          text: (
            <FormattedMessage id="pages.inactive" defaultMessage="Inactive" />
          ),
          status: 'Error',
        },
        '0': {
          text: (
            <FormattedMessage id="pages.active" defaultMessage="Active" />
          ),
          status: 'Success',
        },

      },
    },
    {
      title: (
        <FormattedMessage
          id="pages.sp.spBalance"
        />
      ),
      dataIndex: 'spBalance',
      sorter: true,
      hideInForm: true,
      hideInSearch: true,
    },
    {
      title: (
        <FormattedMessage
          id="pages.createTime"
          defaultMessage="Create Time"
        />
      ),
      dataIndex: 'createTime',
      sorter: true,
      valueType: 'dateRange',
      hideInForm: true,
      search: {
        transform: (value) => ({
          startTime: toUTC(value[0]),
          endTime: toUTC(value[1],true)
        })
      },
      render: (_, record) => {
        return formatToLocalTime(record?.createTime);
      }
    },
    {
      title: (
        <FormattedMessage
          id="pages.updateTime"
          defaultMessage="updateTime"
        />
      ),
      dataIndex: 'updateTime',
      sorter: true,
      hideInForm: true,
      hideInSearch: true,
      key: 'updateTime'
    },

    {
      title: <FormattedMessage id="pages.operating" defaultMessage="Operating" />,
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => [
        <a
          key="api"
          onClick={() => {
            setCurrentRow(record);
            handleApiModalOpen(true);
          }}
        >
          <FormattedMessage id="pages.sp.apilist" defaultMessage="API" />
        </a>,
        <a
          key="config"
          onClick={() => {
            makeActive(record.spId, record.spStatus);
            setCurrentRow(record);
          }}
        >
          {record.spStatus == '1' ? (
            <FormattedMessage id="pages.active" defaultMessage="Active" />
          ) : (
            <FormattedMessage id="pages.inactive" defaultMessage="Inactive" />
          )}
        </a>,
        <a key="edit" onClick={() => {
          setCurrentRow(record);
          handleUpdateModalOpen(true); // 打开编辑弹窗
        }}>
          <FormattedMessage
            id="pages.edit"
            defaultMessage="Edit"
          />
        </a>,
      ],
    },
  ];
  const [columnsStateMap, setColumnsStateMap] = useState<
    Record<string, ColumnsState>
  >({
    updateTime: {
      show: false,
    },
  });
  return (
    <div>
      <ProTable<ServiceProvider, API.PageParams>
        headerTitle={intl.formatMessage({
          id: 'pages.searchTable.title',
          defaultMessage: 'Enquiry form',
        })}
        actionRef={actionRef}
        rowKey={(record, index) => `row-${index}`}
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => [

          <Button
            type="primary"
            key="primary"
            onClick={() => {
              handleModalOpen(true);
            }}
          >
            <PlusOutlined /> <FormattedMessage id="pages.sp.new" defaultMessage="New" />
          </Button>

        ]}
        request={pagedAPi}
        columns={columns}
        columnsState={{
          value: columnsStateMap,
          onChange: setColumnsStateMap,
        }}


      />

      <EditForm visible={createModalOpen} onCancel={() => {
        handleModalOpen(false)
      }}
        onSuccess={function (): void {
          handleModalOpen(false)
          setCurrentRow(undefined);
          if (actionRef.current) {
            actionRef.current.reload();
          }
        }} />
      {/* 编辑表单 */}
      {currentRow && (
        <EditForm
          visible={updateModalOpen}
          values={currentRow}
          onCancel={() => {
            handleUpdateModalOpen(false);
            setCurrentRow(undefined);
          }}
          onSuccess={() => {
            handleUpdateModalOpen(false);
            setCurrentRow(undefined);
            actionRef.current?.reload();
          }}
        />
      )}
      {currentRow && (
      <ApiRelationModal
        visible={apiModalOpen}
        onCancel={() => {
          handleApiModalOpen(false);
          setCurrentRow(undefined);
            actionRef.current?.reload();
        }}
        spId={currentRow?.spId}
      />
      )}

    </div>
  );
};

export default TableList;
